from flask import Flask, request, jsonify
import traceback
import json
import argparse
from util.log_util import LogUtil
#from deal import process
from process_data import process
import re
import datetime

app = Flask(__name__)
app.config["JSON_AS_ASCII"] = False

logger = LogUtil.logger(write_to_file=True, log_file_name="./logs/deal_interface")

def parse_args():
    parser = argparse.ArgumentParser(description="应用参数")
    parser.add_argument("-H", "--host", type=str, default="0.0.0.0", help="监听的IP地址")
    parser.add_argument("-P", "--port", type=int, default=6000, help="监听的端口号")
    return parser.parse_args()

def result(status, message, data=None):
    res = {
        "status": status,
        "message": message
    }
    if data is not None:
        res["data"] = data
    result_log = json.dumps(res, indent=2, ensure_ascii=False)
    logger.info(f"返回结果\n{result_log}")
    return jsonify(res)
def get_label_id_name():
    label_id_name={}
    with open("label.conf","r") as fr:
        for line in fr:
            values=line.strip().split("_")
            if len(values) !=3 or str(values[2])!= "1":
                continue
            label_id_name[str(values[1])]=values[0]
    return label_id_name
def data_convert(request_data):
    data = {}
    label_id_name = get_label_id_name()
    keys = ['is_gprs_over', 'is_gsm_over', 'gprs_all', 'gsm_all', 'gprs_residua', 'gsm_residua', 'avg_day_gprs',
            'avg_day_gsm', 'suf_current_day_count', 'avg_three_month_gsm_count', 'avg_three_month_gprs_count',
            'avg_three_month_gprs_fee', 'avg_three_month_gsm_fee', 'tcw_gprs_fee1', 'tcw_gsm_fee1', 
            'gprs_all1','gprs_all2','gprs_all3','gprs_main_all1','gprs_main_all2','gprs_main_all3', 
            'tcw_gprs1', 'tcw_gprs_fee3', 'tcw_gsm_fee3', 'tcw_gprs3', 'tcw_gsm3', 
            'gsm_zj1','gsm_zj2','gsm_zj3','gsm_main_all1','gsm_main_all2','gsm_main_all3', 
            'tcw_gsm1', 'tcw_gprs_fee2', 'tcw_gsm_fee2', 'tcw_gprs2', 'tcw_gsm2', 'is_over_activity',
            'pre_day_num', 'current_month_num', 'next_day_num', 'next_month_num', 'now_prod_value','now_reduce_price',
            'now_prod_gprs', 'now_prod_gsm', 'avg_three_month_gsm', 'avg_three_month_gprs','top_count']
    if "get_all_labels" in request_data:
        data["get_all_labels"] = 1
        return data
    for key in keys:
        if key not in request_data:
            data[key] = 0
        else:
            value = request_data[key]
            if isinstance(value, int) or isinstance(value, float):
                data[key] = value
            elif isinstance(value, str):
                match = re.match(r"^\d+(\.\d+){0,1}$", value)
                if match is None:
                    data[key] = 0
                elif "." in value:
                    data[key] = float(value)
                else:
                    data[key] = int(value)
    data['productDesc'] = request_data.get('templateBaseInfo', {}).get('productDesc', '')
    data['top_count'] = request_data.get('templateBaseInfo', {}).get('top_count', '')
    label_list = request_data.get('templateLabelList', [])
    label_level={}
    for var in label_list:
        if "id" not in var or "labelId" not in var or "labelName" not in var:
            continue
        if var["id"] == "" and var["labelName"]:
            continue
        level = var["labelOrder"]
        if level == "":
            continue
            #level = 1
        else:
            level = int(var["labelOrder"])
        if var["labelName"] == "" and var["id"] in label_id_name:
            nid = var["id"]
            label_level[label_id_name[nid]] = level
        else:
            label_level[var["labelName"]] = level
    data["label_level"] = label_level
    return data

@app.route("/10086_market_script_371", methods=["POST"])
def interface():
    try:
        year = datetime.datetime.now().year
        month = datetime.datetime.now().month
        day = datetime.datetime.now().day
        hour = datetime.datetime.now().hour
        minute = datetime.datetime.now().minute
        second = datetime.datetime.now().second
        data = request.get_json()
                
        if (data is None) or (not isinstance(data, dict)):
            logger.info(f"请求参数 {data}")
            return result(400, "非json格式参数")
        data_log = json.dumps(data, indent=2, ensure_ascii=False)
        logger.info(f"请求参数\n{data_log}")
        data = data_convert(data)
        data_log = json.dumps(data, indent=2, ensure_ascii=False)
        logger.info(f"入参\n{data_log}")
        # return result(200, "成功", data=data)
        p = process(data)
        # label_dict, first_chi_str, scene_chi_str = p.label_match()
        out_data = p.out_content()
        return result(200, "成功", data=out_data)
    except Exception:
        # traceback.print_exc()
        error_message = traceback.format_exc()
        logger.error(f"\n{error_message}")
        return result(500, "执行失败")


if __name__ == "__main__":
    #print("start")
    logger.info("interface starting!!!!")
    args = parse_args()
    app.run(host=args.host, port=args.port, threaded=True)
